<template>
  <div>
    <a-card title="修改密码" :bordered="false">
      <a-form
        :model="editPasswordForm"
        :style="{ width: '600px' }"
        @submit="handleOk"
      >
        <a-form-item label="原密码" validate-trigger="input" required>
          <a-input-password
            v-model="editPasswordForm.oldPass"
            :style="{ width: '320px' }"
            placeholder="请输入现在使用的密码"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="新密码" validate-trigger="input" required>
          <a-input-password
            v-model="editPasswordForm.newPassword"
            :style="{ width: '320px' }"
            placeholder="请输入新密码"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="确认新密码" validate-trigger="input" required>
          <a-input-password
            v-model="editPasswordForm.rePass"
            :style="{ width: '320px' }"
            placeholder="请再次输入新密码"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="操作">
          <a-button :loading="formLoading" html-type="submit" type="primary">保存</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import { changePassword } from '@/api/login';
import useCurrentInstance from '@/hooks/useCurrentInstance';
import useUser from '@/hooks/user';
import { md5 } from '@/utils/md5';
import { Message } from '@arco-design/web-vue';
import { reactive, ref } from 'vue';

  const { logout } = useUser();
  // 获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  interface formInterface {
    oldPass: string | number;
    newPassword: string | number;
    rePass: string | number;
  }
  const formLoading = ref<boolean>(false);
  const editPasswordForm = reactive<formInterface>({
    oldPass: '',
    newPassword: '',
    rePass: '',
  });
  function handleOk() {
    if (editPasswordForm.rePass !== editPasswordForm.newPassword) {
      Message.error('两次输入密码不一致');
      return;
    }
    const params = {
      password: md5(editPasswordForm.oldPass),
      newPassword: md5(editPasswordForm.newPassword),
    
    };

    const formData = new FormData();
    formData.append('password', params.password);
    formData.append('newPassword', params.newPassword);
  
    changePassword(formData).then((res) => {
      if (res.data.success) {
        modal.confirm({
          title: '修改密码成功',
          content: '修改密码成功，需重新登录',
          onOk: async () => {
            logout();
          },
        });
      }
    });
  }
</script>

<style lang="less" scoped></style>
